import qrcode
from PIL import Image
import random
from urllib.parse import unquote
from io import BytesIO
import web

urls = (
  '/huaji_QR', 'huaji_QR'
)

app = web.application(urls, globals())

class huaji_QR:
    def GET(self):
        qr = qrcode.QRCode(
            border=1
        )

        qr.add_data(unquote(web.input().text))
        qr.make(fit=True)
        matrix = qr.get_matrix()

        tieba = []
        for n in range(0,33):
            tieba.append(Image.open("tieba/%d.png" % n))

        size = (len(matrix[0]) * 30, len(matrix) * 30)
        new_pic = Image.new("RGB", size)

        box = [0, 0]

        for y in matrix:
            for x in y:
                if not x:
                    new_pic.paste(tieba[random.randint(0,32)], tuple(box))
                box[0] += 30
            box[0] = 0
            box[1] += 30
        img = BytesIO()
        new_pic.save(img, format="jpeg")
        web.header('Content-Type','image/jpg')
        return img.getvalue()

if __name__ == "__main__":
    app.run()